import axios from "axios";
import { ElMessage } from 'element-plus'
import { base } from '../conf.js'

axios.defaults.withCredentials = true // 让ajax携带cookie

const service = axios.create({
  baseURL: base.baseUrl,
  timeout: 30000 ,
  withCredentials: false,
})

import store from '../store'
service.interceptors.request.use(request => {
	const { token,ipinfo:{ip,id} } = store.getters
	if (token && token!= undefined)
		request.headers['SRC-TOKEN'] = token
  if(ip && id)
    request.headers['U-IP'] = `${ip},${id}`
  // if(/\/upload\/./.test(request.url))//文件相关
    // request.headers['Content-Type'] = 'multipart/form-data'
  return request
},
err=>{
  ElMessage.error('无法发送请求')
  return Promise.reject(err.data)
})
//拦截返回值
service.interceptors.response.use(
  response=> {
    const {data:res,data:{code,data,msg}} = response
    if(code)
      if (code == 200)
        return Promise.resolve(data)
      else {
        ElMessage.error(msg)
        return Promise.reject(res)
      }
    else return Promise.resolve(res)
  },
  err=>{
    console.log(err)
    if(!err.request)
      ElMessage.error('请求异常')
    else{
      const { status:code } = err.request
      if(code == 404)
        ElMessage.error('未知的请求')
      else
        ElMessage.error('请求服务器异常')
    }
    return Promise.reject(err)
  }
)
export default service